package edu.nf.project.services.other;

import edu.nf.project.entitys.dto.storeOperation.DishCargo;
import edu.nf.project.entitys.dto.storeOperation.DishDTO;
import edu.nf.project.entitys.entity.storeOperation.convention.cargo.Cargo;
import edu.nf.project.entitys.entity.storeOperation.convention.dish.Dish;
import edu.nf.project.mappers.storeOperation.convention.CargoMapper;
import edu.nf.project.mappers.storeOperation.convention.DishCargoMapper;
import edu.nf.project.mappers.storeOperation.convention.DishDTOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author gjh
 * @Date 2025/6/18
 * @Description:
 */
@Service
public class DishInventoryCheckService {

    @Autowired
    private DishDTOMapper dishMapper;

    @Autowired
    private DishCargoMapper dishCargoMapper;

    @Autowired
    private CargoMapper cargoMapper;

    public String checkAndUpdateDishStatus() {
        List<DishDTO> allDishes = dishMapper.findAllActiveDishes(); // 只查状态为“出售”的菜品
        List<Cargo> allCargo = cargoMapper.findAll();

        // 真实库存（不再扣减）
        Map<Integer, Integer> stockMap = new HashMap<>();
        for (Cargo c : allCargo) {
            stockMap.put(c.getCargoId(), c.getStockQuantity());
        }

        // 菜品-食材 映射
        Map<Integer, List<DishCargo>> dishToCargo = new HashMap<>();
        for (DishDTO dish : allDishes) {
            dishToCargo.put(dish.getDishId(), dishCargoMapper.findByDishId(dish.getDishId()));
        }

        int okCount = 0;
        int offCount = 0;
        StringBuilder resultMsg = new StringBuilder();

        for (DishDTO dish : allDishes) {
            boolean canMake = true;
            List<DishCargo> needs = dishToCargo.getOrDefault(dish.getDishId(), List.of());

            for (DishCargo dc : needs) {
                int stock = stockMap.getOrDefault(dc.getCargoId(), 0);
                if (stock < dc.getQuantityNeeded()) {
                    canMake = false;
                    break;
                }
            }

            if (canMake) {
                dishMapper.markDishAsOn(dish.getDishId()); // 设置为“出售”
                resultMsg.append("✅ ").append(dish.getDishName()).append("：库存充足\n");
                okCount++;
            } else {
                dishMapper.markDishAsOff(dish.getDishId()); // 设置为“下架”
                resultMsg.append("❌ ").append(dish.getDishName()).append("：库存不足\n");
                offCount++;
            }
        }

        resultMsg.append("\n✅ 可制作菜品：").append(okCount).append(" 个\n");
        resultMsg.append("❌ 下架菜品：").append(offCount).append(" 个\n");

        return resultMsg.toString(); // 可用于日志或前端返回
    }
}
